package com.ext.aic.components;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.text.TextUtils;
import android.text.style.ReplacementSpan;

import java.util.ArrayList;
import java.util.List;

public class RectCornerSpan extends ReplacementSpan {
    private String mText;
    private int mBackgroundColor;
    private float mPadding;
    private Paint mPaint = new Paint();
    private float mCornerRadius;
    private float mMaxWidth;
    private List<String> mLines = new ArrayList<>();
    private float mLineHeight;

    public RectCornerSpan(String text, int bgColor, int textColor,
                          float paddingDp, float cornerRadiusDp,
                          float textSizeSp, float maxWidthDp, float lineHeightDp) {
        mText = text;
        mBackgroundColor = bgColor;

        mPadding = dpToPx(paddingDp);
        mCornerRadius = dpToPx(cornerRadiusDp);
        float mTextSize = spToPx(textSizeSp);
        mMaxWidth = dpToPx(maxWidthDp);

        mPaint.setAntiAlias(true);
        mPaint.setTextSize(mTextSize);
        mPaint.setColor(textColor);

        // 计算默认行高（基于字体度量）
//        Paint.FontMetrics metrics = mPaint.getFontMetrics();
//        float defaultLineHeight = metrics.descent - metrics.ascent;
        float defaultLineHeight = 16;
        // 用户设置行高，如果 lineHeightDp > 0 则使用，否则用默认值
        mLineHeight = (lineHeightDp > 0) ? dpToPx(lineHeightDp) : defaultLineHeight;

        calculateLines();
    }

    @Override
    public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
        float maxLineWidth = 0;
        for (String line : mLines) {
            float lineWidth = mPaint.measureText(line);
            maxLineWidth = Math.max(maxLineWidth, lineWidth);
        }
        int totalWidth = (int) (maxLineWidth + 2 * mPadding);

        Paint.FontMetrics metrics = mPaint.getFontMetrics();
        mLineHeight = metrics.descent - metrics.ascent;
        float totalHeight = mLineHeight * mLines.size() + 2 * mPadding;

        if (fm != null) {
            fm.ascent = (int) (metrics.ascent - mPadding);
            fm.descent = (int) (mLineHeight * mLines.size() + mPadding / 2);
            fm.top = fm.ascent;
//            fm.bottom = (int) (fm.descent + (mLines.size() - 1) * mLineHeight);
            fm.bottom= (int) totalHeight;
        }
        return totalWidth;
    }

    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end,
                     float x, int top, int y, int bottom, Paint paint) {
        Paint bgPaint = new Paint(mPaint);
        bgPaint.setColor(mBackgroundColor);

        float totalHeight = mLineHeight * mLines.size() + 2 * mPadding;
        RectF rect = new RectF(x, top, x + getWidth(), top + totalHeight);
        canvas.drawRoundRect(rect, mCornerRadius, mCornerRadius, bgPaint);

        float textY = top + mPadding - mPaint.getFontMetrics().ascent;
        for (String line : mLines) {
            canvas.drawText(line, x + mPadding, textY, mPaint);
            textY += mLineHeight;
        }
    }

    private float getWidth() {
        float maxLineWidth = 0;
        for (String line : mLines) {
            maxLineWidth = Math.max(maxLineWidth, mPaint.measureText(line));
        }
        return maxLineWidth + 2 * mPadding;
    }

    public void updateMaxWidth(float newMaxWidthDp) {
        mMaxWidth = dpToPx(newMaxWidthDp);
        calculateLines();
    }

    private void calculateLines() {
        mLines.clear();
        if (TextUtils.isEmpty(mText)) return;

        float availableWidth = mMaxWidth - 2 * mPadding;
        if (availableWidth <= 0) {
            mLines.add(mText);
            return;
        }

        int currentPos = 0;
        while (currentPos < mText.length()) {
            int breakPos = mPaint.breakText(mText, currentPos, mText.length(),
                    true, availableWidth, null);
            if (breakPos == 0) {
                // 处理无法换行的超长单词（强制截断）
                mLines.add(mText.substring(currentPos));
                break;
            }
            mLines.add(mText.substring(currentPos, currentPos + breakPos));
            currentPos += breakPos;
        }
    }


    private float dpToPx(float dp) {
        return dp * android.content.res.Resources.getSystem().getDisplayMetrics().density;
    }

    private float spToPx(float sp) {
        return sp * android.content.res.Resources.getSystem().getDisplayMetrics().scaledDensity;
    }
}
